package com.es.disped.web.controller.menurole;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.es.disped.api.menurole.MenuRoleService;
import com.es.disped.common.model.MsgModel;
import com.es.disped.core.controller.BaseController;
import com.es.disped.dao.model.MenuNode;
import com.es.disped.dao.model.MenuRoleRel;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(value="为角色管理菜单")
@Controller
@RequestMapping("/manage/role/menu")
public class MenuRoleController extends BaseController {
	
	private final String NAMESPACE="com.es.disped.dao.mapper.menu.MenuCustomMapper";

	@Autowired
	MenuRoleService menuRoleService;
	
	@ApiOperation(value="为角色添加菜单",response=MsgModel.class,httpMethod="POST",notes="为角色添加菜单-管理端")
	@RequiresPermissions(value= {"admin:save","sys:save"},logical=Logical.OR)
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public @ResponseBody MsgModel add(@RequestBody @ApiParam() MenuRoleRel menuRoleRel)
	{
		int count=0;
		if(Optional.of(menuRoleRel)
				.filter(roleId->menuRoleRel.getRoleId()!=null)
				.filter(menuId->menuRoleRel.getMenuId()!=null)
				.isPresent())
		{
			menuRoleRel.setRelId(getUUID());
			count=menuRoleService.insert(menuRoleRel);
		}
		return new MsgModel(count!=0?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count!=0?"":"赋予菜单失败",count!=0?menuRoleRel:"");
	}
	
	@ApiOperation(value="更新角色菜单",response=MsgModel.class,httpMethod="POST",notes="更新角色菜单-管理端")
	@RequiresPermissions(value= {"admin:update","sys:update"},logical=Logical.OR)
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public @ResponseBody MsgModel update(@RequestBody @ApiParam() MenuRoleRel menuRoleRel)
	{
		int count=0;
		if(Optional.of(menuRoleRel)
				.filter(relId->menuRoleRel.getRelId()!=null)
				.filter(roleId->menuRoleRel.getRoleId()!=null)
				.filter(menuId->menuRoleRel.getMenuId()!=null)
				.isPresent())
		{
			count=menuRoleService.updateByPrimaryKey(menuRoleRel);
		}
		return new MsgModel(count!=0?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count!=0?"":"更新角色菜单失败",count!=0?menuRoleRel:"");
	}
	
	@ApiOperation(value="回收角色菜单",response=MsgModel.class,httpMethod="POST",notes="回收角色菜单-管理端")
	@RequiresPermissions(value= {"admin:delete","sys:delete"},logical=Logical.OR)
	@RequestMapping(value="/recycle",method=RequestMethod.POST)
	public @ResponseBody MsgModel recycle(@RequestBody @ApiParam() MenuRoleRel menuRoleRel)
	{
		int count=0;
		if(Optional.of(menuRoleRel)
				.filter(relId->menuRoleRel.getRelId()!=null)
				.isPresent())
		{
			count=menuRoleService.deleteByPrimaryKey(menuRoleRel.getRelId());
		}
		return new MsgModel(count!=0?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count!=0?"":"回收角色菜单失败",count!=0?menuRoleRel:"");
	}
	
	
	@ApiOperation(value="获取 checkbox 形式的树结构，并获取已选中项",response=MsgModel.class,httpMethod="POST",
			notes="获取 checkbox 形式的树结构，并获取已选中项-管理端")
	@RequiresPermissions(value= {"admin:select","sys:select"},logical=Logical.OR)
	@RequestMapping(value="/menuCheckedTree",method=RequestMethod.POST)
    public @ResponseBody MsgModel getMenuCheckedTree(String roleId, String id)
    {
        if (this.isNull(id)) {
            id = "00000000000000000000000000000000";
        }
        
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("roleId", roleId);
        paramMap.put("menuId", id);
        
        List<MenuNode> nodeList = new ArrayList<>();
        List<MenuNode> rootList = this.getService().selectList(NAMESPACE + ".getMenuCheckedNode", paramMap);
        for (MenuNode menuNode : rootList) {
            menuNode.setChildren(getMenuCheckedNode(roleId, menuNode.getId()));
            nodeList.add(menuNode);
        }
        return this.resultMsg(nodeList.size()>0?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
        		nodeList.size()>0?"":"菜单列表为空", nodeList.size()>0?nodeList:"");
    }

    /**
     * 获取 checkbox 形式的树结构，并获取已选中项（为角色管理提供支持）<br>
     *
     * @param roleId 角色Id
     * @param pid     树父Id
     * @return List<MenuNode> 树结构结果集
     */
	private List<MenuNode> getMenuCheckedNode(String roleId, String pid) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("roleId", roleId);
        paramMap.put("menuId", pid);
        List<MenuNode> menuList = this.getService().selectList(NAMESPACE + ".getMenuCheckedNode", paramMap);
        return menuList;
	}
}
